﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Diagnostics;
using System.Windows.Forms;
using System.Net;

using System.Drawing;
using System.ComponentModel;
using System.Management;

using Microsoft.Win32;

namespace GieldaCSharp
{
    public partial class Form1 : Form
    {
        private int OdK;
        private int DoK;
        private int constDo;
        private int constOd;
        private int constN;

        private int N;
        private int St;
        private bool c3isClicked = false;
        private bool zmianaOWN = false;

        private int lastDateOpen;

        private Data data = new Data();

        public Stopwatch stop = new Stopwatch();

        public List<kursV> notowania = new List<kursV>();
        public List<kursV> wolumen = new List<kursV>();
        private Listy listaListy = new Listy();
        private List<string> portfel = new List<string>();

        private NotifyIcon sysTrayIcon;
        private ContextMenu sysTrayMenu;
        private RegistryKey rkApp;

        Composite c;
        Composite c3;
        Border bAll;
        Border b;
        Border b2;
        Border b3;
        Notowania n;

        int pozX;
        int p;
        int pkt_old = -1;

        private bool load = false;
        private string nazwa;

        private List<Label> listLabel = new List<Label>();

        //parametry opcji
        public static bool uruchomPrzyStarcie;
        public static int EMA;
        public static double Infl;
        public static double EMAprp, EMAprm;
        public static double PrK, PrS;
        public static bool zmiana = true;


        #region FORM

        public Form1()
        {
            InitializeComponent();       
        }

        private void Form1_Shown(object sender, EventArgs e)
        {
            Application.DoEvents();
            InitializeTray();
            CreateData();
            DefaultValues();
            if (!InitializeData(nazwa)) return;
            InitializeSettings();
            InitializeLabels();
            CountData();
        }

        private void Form1_FormClosed(object sender, FormClosedEventArgs e)
        {
            sysTrayIcon.Visible = false;
            SaveSettings();
        }

        #endregion

        #region INITIALIZE

        private void InitializeLabels()
        {
            for (int i = 0; i <= 32; i++)
            {
                Label l = new Label();
                Point point = new Point();
                point.X = 0;
                point.Y = 0;

                l.AutoSize = true;
                l.Font = new System.Drawing.Font("Nina", 8.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(238)));
                l.ForeColor = System.Drawing.Color.Gray;
                l.Location = point;
                l.Name = "label";
                l.Size = new System.Drawing.Size(64, 13);
                l.TabIndex = 37;
                l.Text = "";

                labData.Text = data.wezDateDD_MM_YY(data.Dzisiaj());
                labOstLogowanie.Text = data.wezDateDD_MM_YY(lastDateOpen);
                
                pictureBox1.Controls.Add(l);

                listLabel.Add(l);
            }

        }

        private void CreateData()
        {
            rkApp = Registry.CurrentUser.OpenSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", true);
            if (rkApp.GetValue("MyApp") == null)
            {
                uruchomPrzyStarcie = false;
            }
            else
            {
                uruchomPrzyStarcie = true;
            }

            c = new Composite(pictureBox1);
            c3 = new Composite(pictureBox3);
            b = new Border2_3(this.pictureBox1);
            bAll = new BorderAll(this.pictureBox1);
            b2 = new Border1_3(this.pictureBox1);
            b3 = new BorderAll(this.pictureBox3);
            n = new Notowania();

                    
        }

        private void DefaultValues()
        {
            constOd = 20000101;
            OdK = 20000101;
            St = 20000101;
            nazwa = "WIG20";
            
            lastDateOpen = 20000101;
            
            EMA = 50;
            
            Infl = 0;
            EMAprp = 4;
            EMAprm = 4;;
            PrK = 0;
            PrS = 0;

            constDo = data.Dzisiaj();
            DoK = data.Dzisiaj();  
        }

        private bool InitializeData(string _nazwa)
        {
            St = dateSt.Value.Year * 100;
            St += dateSt.Value.Month;
            St *= 100;
            St += dateSt.Value.Day;

            if (OdK >= DoK)
            {
                MessageBox.Show("Od >= Do!", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return false;
            }

            nazwa = _nazwa;
            return true;

        }

        private void InitializeListBox()
        {
            FileStream fs = new FileStream("bin/data.ini", FileMode.OpenOrCreate);
            StreamReader sr = new StreamReader(fs);

            string data = "";
            while (data != null)
            {
                data = sr.ReadLine();
                if (null != data) comboBox1.Items.Add(data);
            }
            sr.Close();
        }

        private void InitializeComboBox(ComboBox comb, List<string> list)
        {
            comb.Items.Clear();
            if (list.Count > 0)
                if (list[0] != null)
                    foreach (string s in list)
                    {
                        comb.Items.Add(s);
                    }
        }

        private void InitializeTray()
        {
            sysTrayMenu = new ContextMenu();
            sysTrayMenu.MenuItems.Add("Show", OnShowed);
            sysTrayMenu.MenuItems.Add("Exit", OnExit);

            sysTrayIcon = new NotifyIcon();
            sysTrayIcon.Text = "Gielda";
            sysTrayIcon.Icon = new Icon(SystemIcons.Application, 40, 40);

            sysTrayIcon.ContextMenu = sysTrayMenu;
            sysTrayIcon.Visible = true;
        }

        private void CountData()
        {
            labAkt.Visible = false;
            Application.DoEvents();          

            stop.Reset(); //resetuje stoper
            stop.Start(); //startuje stoper

            n.WczytajNotowania();
            Console.WriteLine(stop.Elapsed);
            n.LiczDane(St, EMA, EMAprp, EMAprm, PrS, PrK, Infl);
            

            WczytajPortfel();
            InitializeComboBox(comboBox1, Dane.Instance.spolki);
            InitializeComboBox(comboBox2, portfel);

            comboBox1.Text = nazwa;
            Start(nazwa);

            KupSprzedajTray(portfel);
            AktualizujStatystyki(portfel, listPortfel);
            AktualizujStatystyki(Dane.Instance.spolki, listWszystkie);

            load = true;
        }

        private void WczytajPortfel()
        {
            if (!Directory.Exists(Application.StartupPath.ToString() + "\\bin")) Directory.CreateDirectory(Application.StartupPath.ToString() + "\\bin");

            if (File.Exists(Application.StartupPath.ToString() + "\\bin\\portfel.ini"))
            {
                FileStream fs = new FileStream(Application.StartupPath.ToString() + "\\bin\\portfel.ini", FileMode.Open);
                StreamReader sr = new StreamReader(fs);

                portfel.Clear();
                string tmpData = sr.ReadLine();
                do //czytamy caly plik i dane dodajemy do list
                {
                    portfel.Add(tmpData);
                    tmpData = sr.ReadLine();
                }
                while (tmpData != null);
                sr.Close();
            }
        }

        private void InitializeSettings()
        {
            if (!Directory.Exists(Application.StartupPath.ToString() + "\\bin")) Directory.CreateDirectory(Application.StartupPath.ToString() + "\\bin");

            if (File.Exists(Application.StartupPath.ToString() + "\\bin\\settings.ini"))
            {
                FileStream fs = new FileStream(Application.StartupPath.ToString() + "\\bin\\settings.ini", FileMode.Open);
                StreamReader sr = new StreamReader(fs);

                string tmpData = sr.ReadLine();
                
                do //czytamy caly plik i dane dodajemy do list
                {
                    string[] tmp = tmpData.Split('=');
                    switch (tmp[0])
                    {
                        case "OD":
                            {
                                OdK = Int32.Parse(tmp[1]);
                                dateOd.Value = new DateTime(data.wezRok(OdK), data.wezMiesiac(OdK), data.wezDzien(OdK));

                            } break;
                        case "ST":
                            {
                                St = Int32.Parse(tmp[1]);
                                dateSt.Value = new DateTime(data.wezRok(St), data.wezMiesiac(St), data.wezDzien(St));

                            } break;
                        case "NAZWA":
                            {
                                nazwa = tmp[1];                                
                            } break;
                        case "OST":
                            {
                                lastDateOpen = Int32.Parse(tmp[1]);
                            } break;
                        case "EMA":
                            {
                                EMA = Int32.Parse(tmp[1]);
                            } break;
                        case "INFL":
                            {
                                double.TryParse(tmp[1], out Infl);
                            } break;
                        case "PRK":
                            {
                                double.TryParse(tmp[1], out PrK);
                            } break;
                        case "PRS":
                            {
                                double.TryParse(tmp[1], out PrS);
                            } break;
                        case "EMAPRP":
                            {
                                double.TryParse(tmp[1], out EMAprp);
                            } break;
                        case "EMAPRM":
                            {
                                double.TryParse(tmp[1], out EMAprm);
                            } break;
                    }
                    tmpData = sr.ReadLine();
                }
                while (tmpData != null);
                sr.Close();
            }            
        }

        private void SaveSettings()
        {
            if (!Directory.Exists(Application.StartupPath.ToString() + "\\bin")) Directory.CreateDirectory(Application.StartupPath.ToString() + "\\bin");

            FileStream fs = new FileStream(Application.StartupPath.ToString() + "\\bin\\settings.ini", FileMode.OpenOrCreate);
            StreamWriter sw = new StreamWriter(fs);
            
            sw.WriteLine("OD=" + OdK);
            sw.WriteLine("ST=" + St);
            sw.WriteLine("NAZWA=" + nazwa);
            sw.WriteLine("OST=" + data.Dzisiaj());
            sw.WriteLine("EMA=" + EMA);
            sw.WriteLine("INFL=" + Infl);
            sw.WriteLine("PRK=" + PrK);
            sw.WriteLine("PRS=" + PrS);
            sw.WriteLine("EMAPRP=" + EMAprp);
            sw.WriteLine("EMAPRM=" + EMAprm);
            sw.Close();
        }

        #endregion

        #region WYKRESY

        private void Start(string _nazwa)
        {
            load = false;

            if (!InitializeData(_nazwa)) return;

            zmianaOWN = false;

            Clear();            

            if (zmiana)
            {
                n.LiczDane(St, EMA, EMAprp, EMAprm, PrS, PrK, Infl);
                KupSprzedaj(Dane.Instance.spolki, listWszystkieKS);
                KupSprzedaj(portfel, listPortfelKS);
            }
            zmiana = false;

            notowania = Dane.Instance.notowania[nazwa];
            wolumen = Dane.Instance.wolumen[nazwa];
            listaListy = Dane.Instance.listy[nazwa];
            constN = listaListy.N;

            Wykres();
            txtWait.Visible = false;
            WypiszDane();

            Application.DoEvents();
            load = true;
        }

        private void Clear()
        {
            labKursx.Text = "";
            labProcentx.Text = "";
            labWolumenx.Text = "";
            labZyskEMA1.Text = "";
            labZyskEMA2.Text = "";
            labZyskSpolka1.Text = "";
            labZyskSpolka2.Text = "";
            txtMainName.Text = "";
            txtMainValue.Text = "";
            txtMainProcent.Text = "";
            txtMainData.Text = "";
            txtMainKS.Text = "";
            pictureBox1.Image = null;
            pictureBox3.Image = null;

            for (int i = 0; i <= 32; i++)
            {
                listLabel[i].Text = "";
            }
        }

        private void WypiszDane()
        {
            txtMainName.Text = nazwa;
            txtMainValue.Text = notowania[notowania.Count - 1].kurs.ToString();
            Follow(txtMainValue, txtMainName, 20);

            double procent = ((notowania[(notowania.Count - 1)].kurs * 100) / notowania[(notowania.Count - 1) - 1].kurs - 100);

            if (procent == 0)
            {
                txtMainProcent.Text = String.Format("{0:f}%", (procent));
                txtMainProcent.ForeColor = System.Drawing.Color.Black;
            }
            else
                if (procent > 0)
                {
                    txtMainProcent.Text = String.Format("+{0:f}%", (procent));
                    txtMainProcent.ForeColor = System.Drawing.Color.LimeGreen;
                }
                else
                {
                    txtMainProcent.Text = String.Format("{0:f}%", (procent));
                    txtMainProcent.ForeColor = System.Drawing.Color.Red;
                }

            Follow(txtMainProcent, txtMainValue, 20);

            txtMainData.Text = data.wezDateDD_MM_YY(notowania[notowania.Count - 1].dataInt);

            Follow(txtMainData, txtMainProcent, 20);

            if (listaListy.kupnoSprzedazV[listaListy.kupnoSprzedazV.Count - 1].kupno == true)
            {
                txtMainKS.ForeColor = System.Drawing.Color.LimeGreen;
                txtMainKS.Text = "Kupuj";
            }
            if (listaListy.kupnoSprzedazV[listaListy.kupnoSprzedazV.Count - 1].sprzedaz == true)
            {
                txtMainKS.ForeColor = System.Drawing.Color.Red;
                txtMainKS.Text = "Sprzedaj";
            }

            Follow(txtMainKS, txtMainData, 20);

            labZyskSpolka1.Text = "Zysk spolka: ";
            if (listaListy.zyskSpolka > 0) labZyskSpolka2.ForeColor = System.Drawing.Color.LimeGreen;
            else labZyskSpolka2.ForeColor = System.Drawing.Color.Red;
            labZyskSpolka2.Text = String.Format("{0:f}%", listaListy.zyskSpolka);
            Follow(labZyskSpolka2, labZyskSpolka1, 10);

            labZyskEMA1.Text = "Zysk EMA: ";
            if (listaListy.zyskEMA > 0) labZyskEMA2.ForeColor = System.Drawing.Color.LimeGreen;
            else labZyskEMA2.ForeColor = System.Drawing.Color.Red;
            labZyskEMA2.Text = String.Format("{0:f}%", listaListy.zyskEMA);
            Follow(labZyskEMA1, labZyskSpolka2, 10);
            Follow(labZyskEMA2, labZyskEMA1, 10);

            checkEMA.Enabled = true;
            checkzyskEMA.Enabled = true;
            checkBS.Enabled = true;


            txtMainName.Visible = true;
            txtMainValue.Visible = true;
            txtMainData.Visible = true;
            txtMainProcent.Visible = true;
            txtMainKS.Visible = true;
            labData.Visible = true;
            labDataM.Visible = true;
            labOstLogowanie.Visible = true;
            labOstLogowanieM.Visible = true;

        }
                
        private void Wykres()
        {

            //--------------------Wykres Glowny--------------------------------------------------------------- 

            N = c.UstalStart(notowania, OdK, DoK);

            if (N < 15)
            {
                //MessageBox.Show("Poza zakresem!", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                dateOd.Value = new DateTime(data.wezRok(notowania[0].dataInt), data.wezMiesiac(notowania[0].dataInt), data.wezDzien(notowania[0].dataInt));
                dateDo.Value = new DateTime(DateTime.Today.Year, DateTime.Today.Month, DateTime.Today.Day);
                OdK = notowania[0].dataInt;
                DoK = constDo;

                N = c.UstalStart(notowania, OdK, DoK);
            }


            c.Clear();
            c3.Clear();

            //wykres glowny
            c.AddComponent(b, notowania, 3);
            c.AddComponent(b2, wolumen, 2);

            c.Add(new WykresRamka(b), 0);
            c.Add(new WykresRamka(b2), 1);
 
            c.Add(new WykresOsie(listLabel, notowania, b,c.getiOd()), 0);

            c.Add(new WykresLinia(notowania, new Pen(Color.FromArgb(57, 73, 150), 1), b, OdK, DoK, c.getiOd(), c.getiDo()), 0);

            c.Add(new WykresWolumen(wolumen, new Pen(Color.Green, 1), b2, OdK, DoK, c.getiOd(), c.getiDo()), 1);

            if (true == checkEMA.Checked)
            {
                //wskaznik EMA +-
                c.Add(new WykresLinia(listaListy.srEMAPV, new Pen(Color.Green, 1), b, OdK, DoK, c.getiOd(), c.getiDo()), 0);
                c.Add(new WykresLinia(listaListy.srEMAV, new Pen(Color.Silver, 1), b, OdK, DoK, c.getiOd(), c.getiDo()), 0);
                c.Add(new WykresLinia(listaListy.srEMAMV, new Pen(Color.Red, 1), b, OdK, DoK, c.getiOd(), c.getiDo()), 0);
            }

            if (true == checkzyskEMA.Checked)
            {
                //zysk EMA
                c.Add(new WykresLinia(listaListy.zyskEmaV, new Pen(Color.Black, 1), b, OdK, DoK, c.getiOd(), c.getiDo()), 0);
            }

            if (true == checkBS.Checked)
            {
                //punkty kupna sprzedazy EMA

                c.Add(new WykresPunkty(listaListy.srBUYEMAV, new Pen(Color.Lime, 1), Brushes.LimeGreen, b, OdK, DoK, c.getiOd(), c.getiDo()), 0);
                c.Add(new WykresPunkty(listaListy.srSELLEMAV, new Pen(Color.Orange, 1), Brushes.Red, b, OdK, DoK, c.getiOd(), c.getiDo()), 0);
            }

            c.DrawAll();
            c.Refresh();

            //----------------------------Wykres ALL----------------------------------------------------            

            c3.UstalStart(notowania, constOd, constDo);

            c3.AddComponent(b3);

            c3.Add(new WykresRamka(b3), 0);
            c3.Add(new WykresTlo(b3, c.getiOd(), c.getiDo()), 0);
            c3.Add(new WykresLinia(notowania, new Pen(Color.FromArgb(57, 73, 150), 1), b3, constOd, constDo, c3.getiOd(), c3.getiDo()), 0);

            c3.DrawAll();
            c3.Refresh();
        }

        private void KupSprzedaj(List<string> lista, ListView listV)
        {
            int k;
            int s;

            listV.Items.Clear();
            if (lista.Count > 0)
                if (lista[0] != null)
                    foreach (string d in lista)
                    {
                        k = 0;
                        s = 0;

                        int count = Dane.Instance.listy[d].srBUYEMAV.Count;
                        if (count > 0)
                        {
                            k = Dane.Instance.listy[d].srBUYEMAV[count - 1].dataInt;
                        }

                        count = Dane.Instance.listy[d].srSELLEMAV.Count;
                        if (count > 0)
                        {
                            s = Dane.Instance.listy[d].srSELLEMAV[count - 1].dataInt;
                        }

                        if (k != 0 && k > s)
                        {
                            if (k >= lastDateOpen)
                            {
                                ListViewItem item1 = new ListViewItem(d, listV.Items.Count);
                                item1.ForeColor = Color.Green;
                                listV.Items.AddRange(new ListViewItem[] { item1 });
                            }
                        }
                        else
                        {
                            if (s != 0 && s >= lastDateOpen)
                            {
                                ListViewItem item1 = new ListViewItem(d, listV.Items.Count);
                                item1.ForeColor = Color.Red;
                                listV.Items.AddRange(new ListViewItem[] { item1 });
                            }
                        }
                    }

        }

        private void AktualizujStatystyki(List<string> lista, ListView listV)
        {
            listV.Items.Clear();
            Dictionary<string, double> mapa = new Dictionary<string, double>();


            if (lista.Count > 0)
                if (lista[0] != null)
                    foreach (string nazwa in lista)
                    {
                        int count = Dane.Instance.notowania[nazwa].Count - 1;
                        if (count > 0)
                        {
                            if (Dane.Instance.notowania[nazwa][count].dataInt == notowania[notowania.Count - 1].dataInt)
                            {
                                double procent = ((Dane.Instance.notowania[nazwa][count].kurs * 100) / Dane.Instance.notowania[nazwa][count - 1].kurs - 100);
                                mapa.Add(nazwa, procent);
                            }
                        }
                    }

            var items = from k in mapa.Keys
                        orderby mapa[k] descending
                        select k;

            foreach (string nazwa in items)
            {
                ListViewItem item1 = new ListViewItem(nazwa, listV.Items.Count);

                item1.SubItems.Add(String.Format("{0:f}%\n", mapa[nazwa]));

                if(mapa[nazwa] > 0) item1.ForeColor = Color.Green;
                else if (mapa[nazwa] < 0) item1.ForeColor = Color.Red;
                else if (mapa[nazwa] == 0) item1.ForeColor = Color.MediumBlue;
                listV.Items.AddRange(new ListViewItem[] { item1 });
            }

        }

        #endregion

        #region MOUSE

        private void pictureBox1_MouseMove(object sender, MouseEventArgs e)
        {
            if (load)
            {
                if ((e.X < bAll.minXn) || (e.X > bAll.maxXn) || (e.Y <= bAll.minYn) || (e.Y >= bAll.maxYn))
                {
                    pkt_old = -1;
                    c.Refresh();
                    labKursx.Text = "";
                    labProcentx.Text = "";
                    labWolumenx.Text = "";
                }
                else
                {
                    pozX = e.X - b.minXn;
                    p = Convert.ToInt32(((Convert.ToDouble(pozX) / Convert.ToDouble(b.maxXn - b.minXn)) * Convert.ToDouble(N)) + c.getiOd());

                    if (p != pkt_old)
                    {
                        double procent = 0;
                        if (p > 0)
                        {
                            procent = ((notowania[p].kurs * 100) / notowania[p - 1].kurs - 100);
                        }
                        labKursx.Text = String.Format("Data: {0} Kurs: {1:f} Wolumen: {2:f} {3:f}%", data.wezDateDD_MM_YY(notowania[p].dataInt), notowania[p].kurs, wolumen[p].kurs, procent);
                        c.DrawBall(p);
                    }
                    pkt_old = p;
                }
            }
        }

        private void pictureBox1_MouseLeave(object sender, EventArgs e)
        {
            if (load)
            {
                pkt_old = -1;
                c.Refresh();
                labKursx.Text = "";
                labProcentx.Text = "";
                labWolumenx.Text = "";
            }
        }

        private void pictureBox3_MouseMove(object sender, MouseEventArgs e)
        {
            if (load && c3isClicked)
            {

                int pozX = 0;
                if ((e.X < b3.minXn) || (e.X > b3.maxXn) || (e.Y <= b3.minYn) || (e.Y >= b3.maxYn))
                {
                    c3.Refresh();
                }
                else
                {
                    pozX = e.X - b3.minXn;
                    int p = Convert.ToInt32(((Convert.ToDouble(pozX) / Convert.ToDouble(b3.maxXn - b3.minXn)) * Convert.ToDouble(constN)));

                    if (e.Button == MouseButtons.Left)
                    {
                        if (p < c.getiDo())
                        {
                            if ((c.getiDo() - p) >= b3.liczbaPodzialek)
                            {
                                dateOd.Value = new DateTime(data.wezRok(notowania[p].dataInt), data.wezMiesiac(notowania[p].dataInt), data.wezDzien(notowania[p].dataInt));

                                c3.AddComponent(b3);

                                c3.Add(new WykresRamka(b3), 0);
                                c3.Add(new WykresTlo(b3, p, c.getiDo()), 0);
                                c3.Add(new WykresLinia(notowania, new Pen(Color.FromArgb(57, 73, 150), 1), b3, constOd, constDo, c3.getiOd(), c3.getiDo()), 0);

                                c3.DrawAll();
                                c3.Refresh();
                                c3.Clear();
                            }
                        }
                    }
                    if (e.Button == MouseButtons.Right)
                    {
                        if (c.getiOd() < p)
                        {
                            if ((p - c.getiOd()) >= b.liczbaPodzialek)
                            {
                                dateDo.Value = new DateTime(data.wezRok(notowania[p].dataInt), data.wezMiesiac(notowania[p].dataInt), data.wezDzien(notowania[p].dataInt));

                                c3.AddComponent(b3);
                                c3.Add(new WykresRamka(b3), 0);
                                c3.Add(new WykresTlo(b3, c.getiOd(), p), 0);
                                c3.Add(new WykresLinia(notowania, new Pen(Color.FromArgb(57, 73, 150), 1), b3, constOd, constDo, c3.getiOd(), c3.getiDo()), 0);

                                c3.DrawAll();
                                c3.Refresh();
                                c3.Clear();
                            }
                        }
                    }

                }
            }
        }

        private void pictureBox3_MouseDown(object sender, MouseEventArgs e)
        {
            c3isClicked = true;
        }

        private void pictureBox3_MouseUp(object sender, MouseEventArgs e)
        {
            int pozX = 0;
            pozX = e.X - b3.minXn;
            int p = Convert.ToInt32(((Convert.ToDouble(pozX) / Convert.ToDouble(b3.maxXn - b3.minXn)) * Convert.ToDouble(constN)));

            if (e.Button == MouseButtons.Left)
            {
                if ((p > c.getiDo()) || ((c.getiDo() - p) < b.liczbaPodzialek))
                    p = c.getiDo() - Convert.ToInt32(b.liczbaPodzialek);

                if (p < 0) p = 0; //zakres z lewej strony

                dateOd.Value = new DateTime(data.wezRok(notowania[p].dataInt), data.wezMiesiac(notowania[p].dataInt), data.wezDzien(notowania[p].dataInt));

                OdK = notowania[p].dataInt;
                Wykres();
            }
            if (e.Button == MouseButtons.Right)
            {
                if ((c.getiOd() > p) || ((p - c.getiOd()) < b.liczbaPodzialek))
                    p = c.getiOd() + Convert.ToInt32(b.liczbaPodzialek);

                if (p > notowania.Count - 1) p = notowania.Count - 1;
                dateDo.Value = new DateTime(data.wezRok(notowania[p].dataInt), data.wezMiesiac(notowania[p].dataInt), data.wezDzien(notowania[p].dataInt));

                DoK = notowania[p].dataInt;
                Wykres();
            }
        }
        #endregion

        #region CHECKED_CHANGED 

        private void checkEMA_CheckedChanged(object sender, EventArgs e)
        {
            Wykres();
        }

        private void checkzyskEMA_CheckedChanged(object sender, EventArgs e)
        {
            Wykres();
        }

        private void checkBS_CheckedChanged(object sender, EventArgs e)
        {
            Wykres();
        }

        #endregion

        #region 1M_3M_6M_2L_All_Own

        private void but1M_Click(object sender, EventArgs e)
        {
            UstalMiesiac(1);
            Wykres();
        }

        private void but3M_Click(object sender, EventArgs e)
        {
            UstalMiesiac(3);
            Wykres();
        }

        private void but6M_Click(object sender, EventArgs e)
        {
            UstalMiesiac(6);
            Wykres();
        }

        private void but2L_Click(object sender, EventArgs e)
        {
            UstalRok(2);
            Wykres();
        }

        private void butOWN_Click(object sender, EventArgs e)
        {
            if (UstalOwn())
            {
                Wykres();
            }
        }

        private void button1_Click(object sender, EventArgs e)
        {
            UstalAll();
            Wykres();
        }


        private void UstalMiesiac(int ile)
        {

            DoK = DateTime.Today.Year * 100;
            DoK += DateTime.Today.Month;
            DoK *= 100;
            DoK += DateTime.Today.Day;

            if ((DateTime.Today.Month - ile) < 1)
            {
                OdK = (DateTime.Today.Year - 1) * 100;
                OdK += (12 + (DateTime.Today.Month - ile));
                OdK *= 100;
                OdK += DateTime.Today.Day;
            }
            else
            {
                OdK = DateTime.Today.Year * 100;
                OdK += (DateTime.Today.Month - ile);
                OdK *= 100;
                OdK += DateTime.Today.Day;
            }
        }

        private void UstalRok(int ile)
        {
            DoK = DateTime.Today.Year * 100;
            DoK += DateTime.Today.Month;
            DoK *= 100;
            DoK += DateTime.Today.Day;

            OdK = (DateTime.Today.Year - ile) * 100;
            OdK += DateTime.Today.Month;
            OdK *= 100;
            OdK += DateTime.Today.Day;
        }

        private bool UstalOwn()
        {
            OdK = dateOd.Value.Year * 100;
            OdK += dateOd.Value.Month;
            OdK *= 100;
            OdK += dateOd.Value.Day;

            DoK = dateDo.Value.Year * 100;
            DoK += dateDo.Value.Month;
            DoK *= 100;
            DoK += dateDo.Value.Day;

            if (DoK <= OdK)
            {
                MessageBox.Show("Data poczatkowa musi byc wieksza od koncowej!", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return false;
            }

            return true;
        }

        private void UstalAll()
        {
            DoK = DateTime.Today.Year * 100;
            DoK += DateTime.Today.Month;
            DoK *= 100;
            DoK += DateTime.Today.Day;

            OdK = 20000101;
        }

        #endregion
        
        #region MENU_STRIP

        private void oProgramieToolStripMenuItem_Click(object sender, EventArgs e)
        {
            MessageBox.Show("Copyright (c) 2012\nJozwiak Adrian\nJozwiak Wojciech\n", "About");
        }

        private void portfelToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Portfel p = new Portfel(Dane.Instance.spolki, portfel);
            p.Show();
            while (!p.IsDisposed)
            {
                Application.DoEvents();
            }
            WczytajPortfel();

            if (uruchomPrzyStarcie)
            {
                rkApp.SetValue("MyApp", Application.ExecutablePath.ToString());
            }
            else
            {
                rkApp.DeleteValue("MyApp", false);
            }
            if (zmiana) Start(nazwa);

            InitializeComboBox(comboBox2, portfel);
            AktualizujStatystyki(portfel, listPortfel);
            KupSprzedaj(Dane.Instance.spolki, listWszystkieKS);
            KupSprzedaj(portfel, listPortfelKS);
        }

        private void koniecToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Application.Exit();
        }

        #endregion

        #region DATE_CHANGE

        protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
        {
            //wyjscie z trybu full screen klawiszem ESC
            const int WM_KEYDOWN = 0x100;
            if (msg.Msg == WM_KEYDOWN)
            {
                if (keyData == Keys.Enter)
                {
                    if (zmianaOWN)
                    {
                        if (UstalOwn())
                        {
                            Wykres();
                        }
                    }
                    if (zmiana)
                    {
                        Start(comboBox1.Text);
                    }
                }
                if (keyData == Keys.Escape)
                {
                    Application.Exit();
                }
            }
            return base.ProcessCmdKey(ref msg, keyData);
        }

        private void dateSt_ValueChanged(object sender, EventArgs e)
        {
            zmiana = true;
        }

        private void dateDo_ValueChanged(object sender, EventArgs e)
        {
            zmianaOWN = true;
        }

        private void dateOd_ValueChanged(object sender, EventArgs e)
        {
            zmianaOWN = true;
        }

        #endregion

        #region SIZE

        private void button3_Click(object sender, EventArgs e)
        {
            if (550 == this.Size.Height) this.Size = new Size(this.Width, 670);
            else
            {
                if (670 == this.Size.Height) this.Size = new Size(this.Width, 550);
            }
        }

        private void Follow(Label who, Label followBy, int odstep)
        {
            who.Location = new Point(followBy.Location.X + followBy.Size.Width + odstep, who.Location.Y);
        }

        #endregion    

        #region SELECTED_INDEX

        private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
        {
            Start(comboBox1.Text);
        }

        private void comboBox2_SelectedIndexChanged(object sender, EventArgs e)
        {
            Start(comboBox2.Text);
        }

        private void listPortfel_SelectedIndexChanged(object sender, EventArgs e)
        {            
            for (int i = 0; i < listPortfel.Items.Count; i++)
            {
                if (listPortfel.Items[i].Selected == true)
                {
                    Start(listPortfel.Items[i].Text);
                }
            }
        }

        private void listWszystkie_SelectedIndexChanged(object sender, EventArgs e)
        {
            for (int i = 0; i < listWszystkie.Items.Count; i++)
            {
                if (listWszystkie.Items[i].Selected == true)
                {
                    Start(listWszystkie.Items[i].Text);
                }
            }
        }

        private void listWszystkieKS_SelectedIndexChanged(object sender, EventArgs e)
        {
            for (int i = 0; i < listWszystkieKS.Items.Count; i++)
            {
                if (listWszystkieKS.Items[i].Selected == true)
                {
                    Start(listWszystkieKS.Items[i].Text);
                }
            }
        }

        private void listPortfelKS_SelectedIndexChanged(object sender, EventArgs e)
        {
            for (int i = 0; i < listPortfelKS.Items.Count; i++)
            {
                if (listPortfelKS.Items[i].Selected == true)
                {
                    Start(listPortfelKS.Items[i].Text);
                }
            }
        }

        #endregion

        #region TRAY

        private void KupSprzedajTray(List<string> lista)
        {
            bool pokazKupno = false;
            bool pokazSprzedaz = false;
            string kup = "kup: ";
            string sprzedaj = "sprzedaj: ";
            string ks = "";
            int s;
            int k;

            if (lista.Count > 0)
                if (lista[0] != null)
                    foreach (string d in lista)
                    {
                        k = 0;
                        s = 0;

                        int count = Dane.Instance.listy[d].srBUYEMAV.Count;
                        if (count > 0)
                        {
                            k = Dane.Instance.listy[d].srBUYEMAV[count - 1].dataInt;
                        }

                        count = Dane.Instance.listy[d].srSELLEMAV.Count;
                        if (count > 0)
                        {
                            s = Dane.Instance.listy[d].srSELLEMAV[count - 1].dataInt;
                        }

                        if (k != 0 && k > s)
                        {
                            if (k >= lastDateOpen)
                            {
                                kup += d + " ";
                                pokazKupno = true;
                            }
                        }
                        else
                        {
                            if (s != 0 && s >= lastDateOpen)
                            {
                                sprzedaj += d + " ";
                                pokazSprzedaz = true;
                            }
                        }
                    }
            
            if (pokazKupno)
            {
                ks += kup + "\n";
            }
            if (pokazSprzedaz)
            {
                ks += sprzedaj + "\n";
            }

            if (pokazKupno || pokazSprzedaz)
            {
                sysTrayIcon.ShowBalloonTip(1000, "Gielda", ks, ToolTipIcon.Info);
            }
        }

        private void OnExit(object sender, EventArgs e)
        {
            Application.Exit();
        }

        private void OnShowed(object sender, EventArgs e)
        {
            Visible = true;
            ShowInTaskbar = true;
        }

        #endregion

        private void button2_Click(object sender, EventArgs e)
        {
            if (!Directory.Exists(Application.StartupPath.ToString() + "\\bin")) Directory.CreateDirectory(Application.StartupPath.ToString() + "\\bin");

            FileStream fs = new FileStream(Application.StartupPath.ToString() + "\\bin\\portfel.ini", FileMode.OpenOrCreate);
            StreamReader sr = new StreamReader(fs);
            StreamWriter sw = new StreamWriter(fs);

            string name = comboBox1.Text.ToString();
            bool check = true;
            string data = "";
            while (data != null)
            {
                data = sr.ReadLine();
                if (name == data)
                {
                    check = false;
                }
            }

            if (check)
            {
                sr.ReadToEnd();
                sw.WriteLine(name);
            }

            sw.Close();
            sr.Close();

            WczytajPortfel();
            InitializeComboBox(comboBox2, portfel);
            AktualizujStatystyki(portfel, listPortfel);
            KupSprzedaj(Dane.Instance.spolki, listWszystkieKS);
            KupSprzedaj(portfel, listPortfelKS);
            comboBox2.Text = name;
        }

        private void button4_Click(object sender, EventArgs e)
        {
            if (!Directory.Exists(Application.StartupPath.ToString() + "\\bin")) Directory.CreateDirectory(Application.StartupPath.ToString() + "\\bin");

            FileStream fs = new FileStream(Application.StartupPath.ToString() + "\\bin\\portfel.ini", FileMode.Create);
            StreamWriter sr = new StreamWriter(fs);

            comboBox2.Items.Remove(comboBox2.SelectedItem);

            for (int i = 0; i < comboBox2.Items.Count; i++)
            {
                sr.WriteLine(comboBox2.Items[i].ToString());             
            }
            sr.Close();

            WczytajPortfel();
            InitializeComboBox(comboBox2, portfel);
            AktualizujStatystyki(portfel, listPortfel);
            KupSprzedaj(Dane.Instance.spolki, listWszystkieKS);
            KupSprzedaj(portfel, listPortfelKS);

        }
    }
}
